package com.example.wechat;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wechat.adapter.FriendAdapter;
import com.example.wechat.database.FriendDatabaseHelper;
import com.example.wechat.model.Friend;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;

import java.util.List;

public class FriendManagementActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private FriendAdapter adapter;
    private FriendDatabaseHelper dbHelper;
    private List<Friend> friendList;
    private AlertDialog currentDialog; // 添加成员变量来跟踪当前对话框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_management);

        dbHelper = new FriendDatabaseHelper(this);
        recyclerView = findViewById(R.id.friend_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        FloatingActionButton fab = findViewById(R.id.fab_add_friend);
        fab.setOnClickListener(view -> showAddFriendDialog());

        loadFriends();
    }

    private void loadFriends() {
        friendList = dbHelper.getAllFriends();
        adapter = new FriendAdapter(this, friendList);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new FriendAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Friend friend) {
                // 点击好友项的处理
            }

            @Override
            public void onDeleteClick(Friend friend) {
                showDeleteConfirmationDialog(friend);
            }

            @Override
            public void onMoveGroupClick(Friend friend) {
                showMoveGroupDialog(friend);
            }
        });
    }

    private void showAddFriendDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_friend, null);
        TextInputEditText usernameInput = dialogView.findViewById(R.id.username_input);
        TextInputEditText verificationInput = dialogView.findViewById(R.id.verification_input);

        builder.setView(dialogView)
                .setTitle("添加好友")
                .setPositiveButton("添加", null) // 先设置为null，后面再设置监听器
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss());

        currentDialog = builder.create();
        currentDialog.show();

        // 在对话框显示后设置PositiveButton的点击监听器
        currentDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            String username = usernameInput.getText().toString().trim();
            String verification = verificationInput.getText().toString().trim();
            
            if (username.isEmpty()) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建好友对象
            Friend friend = new Friend();
            friend.setId(String.valueOf(System.currentTimeMillis()));
            friend.setUsername(username);
            friend.setNickname(username); // 默认昵称与用户名相同
            friend.setAvatar("default_avatar");
            friend.setGroup("我的好友");
            friend.setRemark(verification);
            friend.setStatus("accepted"); // 直接设置为已接受状态
            
            // 添加到数据库
            long result = dbHelper.addFriend(friend);
            if (result != -1) {
                Toast.makeText(this, "添加好友成功", Toast.LENGTH_SHORT).show();
                loadFriends(); // 重新加载好友列表
                currentDialog.dismiss();
                finish(); // 返回主界面
            } else {
                Toast.makeText(this, "添加好友失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showDeleteConfirmationDialog(Friend friend) {
        new AlertDialog.Builder(this)
                .setTitle("删除好友")
                .setMessage("确定要删除好友 " + friend.getNickname() + " 吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    dbHelper.deleteFriend(friend.getId());
                    loadFriends();
                    Toast.makeText(this, "好友已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void showMoveGroupDialog(Friend friend) {
        List<String> groups = dbHelper.getAllGroups();
        String[] groupArray = groups.toArray(new String[0]);
        
        new AlertDialog.Builder(this)
                .setTitle("移动分组")
                .setItems(groupArray, (dialog, which) -> {
                    friend.setGroup(groupArray[which]);
                    dbHelper.updateFriend(friend);
                    loadFriends();
                    Toast.makeText(this, "已移动到" + groupArray[which], Toast.LENGTH_SHORT).show();
                })
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_friend_management, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_add_group) {
            showAddGroupDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showAddGroupDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_group, null);
        TextInputEditText groupNameInput = dialogView.findViewById(R.id.group_name_input);

        new AlertDialog.Builder(this)
                .setTitle("新建分组")
                .setView(dialogView)
                .setPositiveButton("创建", (dialog, which) -> {
                    String groupName = groupNameInput.getText().toString().trim();
                    
                    if (groupName.isEmpty()) {
                        Toast.makeText(this, "请输入分组名称", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (dbHelper.getAllGroups().contains(groupName)) {
                        Toast.makeText(this, "该分组已存在", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    dbHelper.addGroup(groupName);
                    Toast.makeText(this, "分组已创建", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            dbHelper.close();
        }
        // 确保对话框被关闭
        if (currentDialog != null && currentDialog.isShowing()) {
            currentDialog.dismiss();
        }
    }
} 